<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class Config extends Base
{
    protected $table = 'config';
    const REDIS_CONFIG = 'REDIS:CONFIG:TYPE';//redis 配置
    const REDIS_CONFIG_DATE = 'REDIS:CONFIG:DATE';//redis date 配置


    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function getShareGoodsConfig($type)
    {
        if (empty($type)) {
            $result = DB::table("config")->get();
        } else {
            $result = DB::table("config")->where(['type' => $type])->get();
        }
        if (empty($result)) {
            return null;
        }
        $result = self::objToArray($result);
        $all_data = [];
        $ret_data = [];
        foreach ($result as $k => $v) {
            $all_data[$v['key']] = json_encode($v);
            $ret_data[$v['key']] = $v;
        }
        return $ret_data;
    }

    public function configCache($type)
    {
        //配置文件redis key
        $redis_key = self::REDIS_CONFIG . '-' . $type;
        //获取配置项
        $redis_cache = Redis::get($redis_key);
        do {
            if ($redis_cache) {
                $redis_cache = json_decode($redis_cache, true);
                return $redis_cache;
            }
            $result = DB::table("config")->where(['type' => $type])->get();
            $result = self::objToArray($result);
            $all_data = [];
            $ret_data = [];
            foreach ($result as $k => $v) {
                $all_data[$v['key']] = json_encode($v);
                $ret_data[$v['key']] = $v;
            }
            Redis::set($redis_key, json_encode($ret_data), 'EX', 60);//缓存配置文件60s
            return $ret_data;
        } while (false);
    }

    public function getConfigDate($type, $date_name)
    {
        do {
            //配置文件redis key
            $redis_key = self::REDIS_CONFIG_DATE . '-' . $type;
            //获取配置项
            $redis_date_cache = Redis::get($redis_key);
            if ($redis_date_cache) {
                return $redis_date_cache;
            }
            $result = DB::table("config")->where(['type' => $type])->get();
            $result = array_column(self::objToArray($result), 'value', 'key');
            if (empty($result)) {
                return $result;
            }
            Redis::set($redis_key, $result[$date_name]);
            $this->ttlRedisKey($redis_key);
            return Redis::get($redis_key);
        } while (false);
    }


}
